<template>
  <div class="main">
    <div style="margin:0 3%;width:94%;height:94%">
      <div class="contentForm">
        <el-form ref="selectForm" :model="form" label-width="80px" :inline="true" class="demo-form-inline formSelect" size="small">
          <el-form-item label="事件时间">
            <el-date-picker v-model="form.datetime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleSelectChanged" style="width:400px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="事件分类">
            <el-select v-model="form.category" clearable placeholder="全部分类" :loading="classLoading" loading-text="正在加载中..." no-data-text="暂无数据" @change="handleSelectChanged" @focus="handleEventCategoryFocus" style="width:100px">
              <el-option :label="cate.ch_name" :value="cate.ch_name" v-for="(cate,index) in category" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-col>
            <el-form-item label="事件地点">
              <el-select v-model="form.region" clearable placeholder="全部地点" :loading="addressLoading" loading-text="正在加载中..." no-data-text="暂无数据" @change="handleSelectChanged" @focus="handleEventAddressFocus" style="width:300px">
                <el-option :label="addr.ch_name" :value="addr.ch_name" v-for="(addr,index) in address" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-button size="small" @click="handleReset" icon="el-icon-delete">重置</el-button>
            <el-button type="primary" size="small" @click="handleSelect" icon="el-icon-search">查询</el-button>
            <el-button type="success" size="small" @click="handleDownloadExcel" icon="el-icon-download">导出Excel</el-button>
          </el-col>
        </el-form>
        <common-loading :loading="loading" loadingText="">
          <i slot="loadingIcon" class="el-icon-loading"></i>
        </common-loading>
        <el-table v-if="!loading" :data="eventData" height="calc(100% - 170px)" :row-class-name="tableRowClassName">
          <el-table-column prop="index" label="序号" width="70" class="hidden-lg-and-down"></el-table-column>
          <el-table-column prop="time" label="时间" width="170"></el-table-column>
          <el-table-column prop="address" label="地点"></el-table-column>
          <el-table-column prop="event" label="事件"></el-table-column>
          <el-table-column prop="videoPath" v-if="false"></el-table-column>
          <el-table-column prop="imgPath" v-if="false"></el-table-column>
          <el-table-column label="操作" width="230">
            <template slot-scope="scope">
              <el-button size="mini" type="success" icon="el-icon-view" @click="selectVideo(scope.$index, scope.row)">
                视频
              </el-button>
              <el-button size="mini"  icon="el-icon-view" @click="selectImg(scope.$index, scope.row)">
                图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="pagination" layout="prev, pager, next" v-if="!loading && pageCount>1" :page-count="pageCount" :page-size="pageSize" :current-page.sync="currentPage" @current-change="handleCurrentChange" @prev-click="handlePrevClick" @next-click="handleNextClick">
        </el-pagination>
        <el-dialog :visible.sync="videoVisible" width="40%" class="videoplayer" title="历史视频" @opened="handlePlayerOpened" :before-close="handleVideoClose">
          <video-player ref="videoPlayer" class="video-player vjs-custom-skin" :class="{noVideo:noVideo}" :playsinline="true" :options="playerOptions" @ready="onPlayerReadied($event)" style="width:100%; height: 53%"></video-player>
        </el-dialog>
        <el-dialog :visible.sync="imgVisible" width="40%" class="imgdialog" title="历史图片" @opened="handleImgOpened" >
          <div class="imgContent" style="width:100%; height: 0%; padding-bottom: 60%">
            <img src="" alt="" ref="historyImg" >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import CommonCard from "../components/CommonCard.vue"
import CommonLoading from "../components/CommonLoading.vue"
import util from "../util/util.js"
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/lang/zh-CN'
export default {
  components: {
    CommonCard,
    CommonLoading,
    videoPlayer
  },
  data() {
    return {
      videoVisible: false,
      imgVisible:false,
      loading: false,
      noVideo: true,
      addressLoading: false,
      classLoading: false,
      selectChanged: false,
      imgTitleBgColor: '#FDB546',
      imgBorderColor: '#FDB546',
      form: {
        region: '',
        type: '异常',
        category: '',
        datetime: [],
      },
      eventData: [],
      address: [],
      category: [],
      pageCount: 1,
      currentPage: 1,
      pageSize: 10,
      imgRow:-1,
      videoUrl: '',
      videoRow: -1,
      videoIndex:-1,
      playerOptions: {
        bigPlayButton: false,
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: true, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '3:2', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",
          src: "" //url地址
        }],
        // poster: "/static/videoBackground.png", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          volumePanel: {
            inline: false
          },
          fullscreenToggle: true //全屏按钮
        }
      }
    }
  },
  created() {
    this.fetchData();
  },
  computed: {
    player() {
      return this.$refs.videoPlayer.player;
    },
    imgContainer() {
      return this.$refs.historyImg;
    }
  },
  methods: {
    getDate() {
      let date = new Date();
      let year = date.getFullYear();
      let mouth = date.getMonth();
      let day = date.getDate();
      let startTime = new Date(year, mouth, day, 0, 0);
      let endTime = new Date(year, mouth, day, 23, 59, 59);
      this.form.datetime.push(startTime);
      this.form.datetime.push(endTime);
    },
    getEventAddress() {
      this.addressLoading = true;
      this.$api.historyEvent.historyEventAddress().then(response => {
        this.addressLoading = false;
        if (response.data.code == "6000") {
          this.address = response.data.data;
        } else {
          this.$message({
            message: util.getErrorInfo(response.data.code),
            type: 'error'
          });
        }
      }).catch(error => {
        this.addressLoading = false;
      });
    },
    getEventCategory() {
      this.classLoading = true;
      this.$api.historyEvent.historyEventType().then(response => {
        this.classLoading = false;
        if (response.data.code == "6000") {
          this.category = response.data.data;
        } else {
          this.$message({
            message: util.getErrorInfo(response.data.code),
            type: 'error'
          });
        }
      }).catch(error => {
        this.classLoading = false;
      });
    },
    fetchData() {
      this.loading = true;
      let params = {
        page_size: this.pageSize,
        page_index: this.selectChanged ? 1 : parseInt(this.currentPage),
        start_time: this.form.datetime ? this.form.datetime[0] : '',
        end_time: this.form.datetime ? this.form.datetime[1] : '',
        road_name: this.form.region,
        event: this.form.category
      };
      this.selectChanged = false;
      this.$api.historyEvent.historyEventList(params).then(response => {
        this.loading = false;
        if (response.data.code == "6000") {
          let data = response.data.data.events;
          this.currentPage = response.data.data.index;
          this.pageCount = response.data.data.total_pages;
          this.processData(data);
        } else {
          this.$message({
            message: util.getErrorInfo(response.data.code),
            type: 'error'
          });
        }
      }).catch(error => {
        this.loading = false;
      });
    },
    processData(data) {
      let tmpData = [];
      for (let i in data) {
        let eventobj = {};
        eventobj["index"] = (this.currentPage - 1) * this.pageSize + parseInt(i) + 1;
        eventobj["time"] = data[i]["starttime"];
        eventobj["address"] = data[i]["road_name"];
        eventobj["event"] = data[i]["event"];
        eventobj["videoPath"] = data[i]["v_path"];
        eventobj["imgPath"] = data[i]["p_path"];
        tmpData.push(eventobj);
      }
      this.eventData = tmpData;
    },
    handleSelectChanged() {
      this.selectChanged = true;
    },
    handleEventCategoryFocus(){
        if(this.category.length<=0) this.getEventCategory();
    },
    handleEventAddressFocus(){
        if(this.address.length<=0) this.getEventAddress();
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.event === "行人入侵") {
        return 'warning-row';
      } else if (row.event === "停车") {
        return 'info-row'
      }
      return '';
    },
    handleSelect() {
      this.fetchData();
    },
    handleReset() {
      this.selectChanged = true;
      this.form.region = "";
      this.form.type = "异常";
      this.form.category = "";
      this.form.datetime = [];
    },
    handleVideoClose(){
      this.player.pause();
      this.playerOptions.sources[0].src = '';
      this.videoVisible = false;
    },
    handlePlayerOpened(){
      this.playerOptions.sources[0].src = this.videoRow.videoPath;
      this.player.load();
      this.noVideo = false;
      this.playerOptions.bigPlayButton = true;
    },
    selectVideo(index, row) {
      this.videoVisible = true;
      this.videoRow = row;
      this.videoIndex = index;
    },
    handleImgOpened(){
      this.imgContainer.src = this.imgRow.imgPath;
    },
    selectImg(index, row) {
      this.imgVisible = true;
      this.imgRow = row;
    },
    onPlayerReadied(event) {
      this.player.currentTime(120);
    },
    handleCurrentChange(value) {
      this.currentPage = value;
      this.fetchData();
    },
    handlePrevClick(value) {
      this.currentPage = value;
      this.fetchData();
    },
    handleNextClick(value) {
      this.currentPage = value;
      this.fetchData();
    },
    handleDownloadExcel() {
      this.exportExcel();
    },
    //请求返回的数据是文件流格式 blob
    exportExcel() {
      let params = {
        start_time: this.form.datetime ? this.form.datetime[0] : '',
        end_time: this.form.datetime ? this.form.datetime[1] : '',
        road_name: this.form.region,
        event: this.form.category
      };
      this.$api.historyEvent.exportExcel(params).then(response => { // 处理返回的文件流
        const blob = new Blob([response.data], { type: "application/vnd.ms-excel" });
        const fileName = '历史事件统计.xlsx';
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
    }
  }

}

</script>
<style scoped lang="scss">
@import "../assets/basic.scss";
.main{
	height: 100%;
  padding-top: 3%;
  box-sizing: border-box;
}
.contentForm {
  position: relative;
  overflow: hidden;
  height: 100%;
  border-radius: 4px;
  background-color: $ims-table-bgcolor;
  .formSelect {
    box-sizing: border-box;
    height: 140px;
    padding: 30px 10px 0;
  }
  .formSelect::after {
    clear: both;
    content: " ";
    display: block;
    height: 0;
    width: 0;
    visibility: hidden;
  }
  .table {
    width: 100%;
    background-color: $ims-table-bgcolor;
  }
  .pagination {
    width: 100%;
    text-align: center;
    // background-color: #2481b8;
  }
}
.imgdialog{
    .imgContent {
      height: 400px;
      background: #fff url("/static/imgBackground.png") no-repeat 50%;
      img {
          width: 100%;
          height: 100%;
      }
    }
}
</style>
<style lang="css" scoped>
.imgdialog >>> .el-dialog,.videoplayer >>> .el-dialog{
 background: url("../../static/dialogbg.png") no-repeat ;
  background-size: 100% 100%;
  box-shadow: none;
}

.imgdialog >>> .el-dialog__headerbtn,.videoplayer >>> .el-dialog__headerbtn{
  top: 10px;
  right: 12%;
  }
.imgdialog >>> .el-dialog__close,.videoplayer >>> .el-dialog__close{
  color: #fff;
  font-size: 25px;
}
.imgdialog  >>> .el-dialog__header,.videoplayer >>> .el-dialog__header{
    text-align: center;
}
</style>
